import LanguageMngTs from "../Managers/LanguageMngTs";
import HttpAPIUtil from "../Utils/HttpAPIUtil";
import LogicConfigTs from "../Utils/LogicConfigTs";
import Channels from "../Static/Channels";
import ApkVersionUtil from "../Utils/ApkVersionUtil";
import GameDataUtilTs from "../Utils/GameDataUtilTs";
const { ccclass, property } = cc._decorator;


@ccclass
export class Login2 extends cc.Component {

    // @property(cc.Label)
    // label: cc.Label = null;

    // @property
    // text: string = 'hello';

    @property(cc.Node)
    loginNode: cc.Node = null;

    @property(cc.Node)
    registerNode: cc.Node = null;

    @property(cc.Node)
    forgotNode: cc.Node = null;

    @property(cc.EditBox)
    regNameEb: cc.EditBox = null;

    @property(cc.EditBox)
    regPwEb: cc.EditBox = null;

    @property(cc.EditBox)
    regOtpEb: cc.EditBox = null;

    @property(cc.EditBox)
    loginNameEb: cc.EditBox = null;

    @property(cc.EditBox)
    loginPwEb: cc.EditBox = null;

    @property(cc.EditBox)
    forNameEb: cc.EditBox = null;

    @property(cc.EditBox)
    forPwEb: cc.EditBox = null;

    @property(cc.EditBox)
    forOtpEb: cc.EditBox = null;

    @property(cc.Label)
    forgotOtpBtnLabel: cc.Label = null;

    @property(cc.Button)
    forgotOtpBtn: cc.Button = null;

    @property(cc.Label)
    otpBtnLabel: cc.Label = null;

    @property(cc.Button)
    otpBtn: cc.Button = null;

    @property(cc.Node)
    introduceNode: cc.Node = null;

    @property(cc.Node)
    allLoginNode: cc.Node = null;

    @property(cc.Node)
    allNode: cc.Node = null

    @property(cc.Sprite)
    logoSprite : cc.Sprite = null

    @property(cc.SpriteFrame)
    frameLogo666 : cc.SpriteFrame = null

    @property(cc.SpriteFrame)
    frameLogoRoz : cc.SpriteFrame = null

    @property(cc.Label)
    lang_label1: cc.Label = null;

    @property(cc.Label)
    lang_label2: cc.Label = null;

    @property(cc.Label)
    lang_label3: cc.Label = null;

    @property(cc.Label)
    lang_label4: cc.Label = null;

    @property(cc.Label)
    lang_label5: cc.Label = null;

    @property(cc.Label)
    lang_label6: cc.Label = null;

    @property(cc.Label)
    lang_label7: cc.Label = null;

    @property(cc.Label)
    lang_label8: cc.Label = null;

    @property(cc.Label)
    lang_label9: cc.Label = null;

    @property(cc.Label)
    lang_label10: cc.Label = null;

    @property(cc.Label)
    lang_label11: cc.Label = null;

    @property(cc.Label)
    lang_label12: cc.Label = null;

    @property(cc.Label)
    lang_label13: cc.Label = null;

    @property(cc.Label)
    lang_label14: cc.Label = null;


    public secretArray: Array<number> = [];
    /**秘籍-- */
    public targetArray: Array<number> = [];
    public firstSend: boolean = true;
    public firstForSend: boolean = true;

    public maxCount: number = 0;
    public maxForGotCount: number = 0;

    public secretClickTimer = null;
    public isBtnLogin: boolean = true;

    public pinId: number = 0;
    public pinIdFro: number = 0;

    /** 0---Login   1---Regist   2----forgot */
    public typeNodeNum: number = 1;

    public _offsetY: number = 0;
    private _focusEb : cc.Node = null;   //最后一次触摸的

    constructor() {
        super();
    }
    // LIFE-CYCLE CALLBACKS:

    public onLoad() {
        this.secretArray = [];
        this.targetArray = [1, 2, 1, 1, 2];

        this.firstSend = true;
        this.firstForSend = true;
        this.isBtnLogin = true;
        this.typeNodeNum = 1;
        this._initBgLogo()
        this.changeToRegistPage();

        let self = this
        if(ApkVersionUtil.getApkVersionCode() < 10003){
            let hor = GameDataUtilTs.getIsAllHorizontal() || false
            if(!hor){
                //竖屏
                // cc.gg.gameDataUtil.addKeyboardUpCb("loginup", (keyboardHeight) => {
                //     console.log("键盘方法：loginup,下移" + keyboardHeight + "像素");
                //     self.allNode.y -= keyboardHeight;
                //     self._offsetY = keyboardHeight;
                // });
                //
                // cc.gg.gameDataUtil.addKeyboardDownCb("logindown", (keyboardHeight) => {
                //     console.log("键盘方法：logindown,上移" + keyboardHeight + "像素");
                //     self.allNode.y += this._offsetY;
                // });
            }
        }else { //横屏登录
            let hor = GameDataUtilTs.getIsAllHorizontal() || false
            if(hor){
                cc.gg.gameDataUtil.addKeyboardUpCb("loginup", (keyboardHeight) => {
                    // if(this._focusEb && this._focusEb.y < keyboardHeight){
                    //     let minus = keyboardHeight - this._focusEb.y + 20
                    //     console.log("cocos：内容整体上移",minus)
                    //     self.allNode.y += minus;
                    //     self._offsetY = minus;
                    // }

                    // if(this._focusEb){
                    //     let minus = this._focusEb.y - keyboardHeight + keyboardHeight - 50
                    //     self.allNode.y -= minus
                    //     self._offsetY = minus
                    // }
                });

                cc.gg.gameDataUtil.addKeyboardDownCb("logindown", (keyboardHeight) => {
                    // console.log("cocos：内容整体下移",this._offsetY)
                    // self.allNode.y -= this._offsetY;
                    // this._focusEb = null

                    // if(this._focusEb){
                    //     self.allNode.y += this._offsetY
                    //     this._focusEb = null
                    // }
                });
            }
        }


        var cur = cc.director.getRunningScene();
        if (typeof cur == "object" && cur.name == "LoginHTs") {
            this.language();
        }

    }

    _initBgLogo(){
        if(!this.logoSprite) return
        let channel = cc.gg.gameDataUtil.getPakageChannel() || null;
        console.log("当前的渠道号：",channel)
        if(channel === Channels.CHANNEL_JN){
            console.log("在登录页使用666LOGO")
            this.logoSprite.spriteFrame = this.frameLogo666
        }else {
            console.log("在登录页使用RozLOGO")
            this.logoSprite.spriteFrame = this.frameLogoRoz
        }
    }

    onNeedFitEditBoxClicked (event) {
        let ebNode = event.node
        this._focusEb = ebNode.parent
    }

    public start() {
        cc.gg.tdUtil.doSendTdEvent("open_login", null);
    }

    public language() {
        this.lang_label1.string = LanguageMngTs.getSentence(243);  //Play instant Rummy anytime
        this.lang_label2.string = LanguageMngTs.getSentence(244);  //Jeeto endless cash
        this.lang_label3.string = LanguageMngTs.getSentence(245);  // Instant Cash on Sign up
        this.lang_label4.string = LanguageMngTs.getSentence(246) + "\n" + LanguageMngTs.getSentence(247);  // Welcome! Log in & start WINNING!
        this.lang_label5.string = LanguageMngTs.getSentence(248);  // Forgot password?
        this.lang_label6.string = LanguageMngTs.getSentence(249);  // Not a Member yet?
        this.lang_label7.string = LanguageMngTs.getSentence(250);  // Join Now?
        this.loginNameEb.placeholder = LanguageMngTs.getSentence(251);  // Phone Number
        this.loginPwEb.placeholder = LanguageMngTs.getSentence(252);  // Password
        this.lang_label8.string = LanguageMngTs.getSentence(253);   // Login
        this.regNameEb.placeholder = LanguageMngTs.getSentence(251);   // Phone Number
        this.regPwEb.placeholder = LanguageMngTs.getSentence(254);  // New Password
        this.regOtpEb.placeholder = LanguageMngTs.getSentence(255);  // Please enter OTP
        this.lang_label9.string = LanguageMngTs.getSentence(256);   // Have an account already?
        this.lang_label10.string = LanguageMngTs.getSentence(257);  // Login now!
        this.lang_label11.string = LanguageMngTs.getSentence(258);   // Register
        this.forNameEb.placeholder = LanguageMngTs.getSentence(251);   // Phone Number
        this.forPwEb.placeholder = LanguageMngTs.getSentence(254);  // New Password
        this.forOtpEb.placeholder = LanguageMngTs.getSentence(255);   // Please enter OTP
        this.lang_label12.string = LanguageMngTs.getSentence(259);   // Reset And Login
        this.lang_label13.string = LanguageMngTs.getSentence(257);  // Login now!
        this.lang_label14.string = LanguageMngTs.getSentence(256);   // Have an account already?
    }

    // update (dt) {}

    public onDestroy() {
        cc.gg.gameDataUtil.removeKeyboardUpCb("loginup");
        cc.gg.gameDataUtil.removeKeyboardDownCb("logindown");
    }

    public startTestClick(secret) {
        if (this.secretClickTimer) {
            this.unschedule(this.secretClickTimer);
            this.secretClickTimer = null;
        }

        let cb = () => {
            this.secretArray = [];
            cc.log("清空连续点击");
        };

        this.secretArray.push(secret);
        if (this.checkSecretClick()) {
            this.secretArray = [];
            cc.log("密码输入成功！");
            this.doGuestLogin();
        } else {
            this.secretClickTimer = cb.bind(this);
            this.scheduleOnce(this.secretClickTimer, 1);
        }
    }

    public checkSecretClick() {
        for (let i = 0; i < this.targetArray.length; i++) {
            let nowSec = this.secretArray[i];
            if (nowSec !== this.targetArray[i])
                return false;
        }
        return true;
    }

    public onLoginTestButtonsClicked(event) {
        let btnName = event.target.name;
        if (btnName === "login_icon_pokers") {
            this.startTestClick(1);
        } else if (btnName === "login_icon_manycrash") {
            this.startTestClick(2);
        }
    }

    public async doGuestLogin() {
        await cc.gg.toastMgr.showNetWaitting();
        // let result = await cc.gg.httpUtil.httpPost("/user/login/guest", { channel: cc.gg.gameDataUtil.getPakageChannel() });
        let result = await cc.gg.httpUtil.httpPost("/user/login/guest", { channel: "guest" });
        if (!result.succ) {
            cc.gg.toastMgr.removeNetWaitting();
            cc.logfl(`游戏登陆失败: ${result.msg}`);
            return;
        }
        cc.logfl(`游戏登陆成功, 用户名: ${result.data.username} 密码: ${result.data.password}`);
        console.log(result.data);
        let token = result.data.token;

        cc.sys.localStorage.setItem('user_token', token);
        cc.sys.localStorage.setItem("login_method", "guest");
        cc.gg.httpUtil.setUserToken(token);
        cc.gg.toastMgr.removeNetWaitting();

        cc.gg.gameDataUtil.isRegister = true;
        cc.gg.gameCtl.goLobby(token);
    }

    public async onLoginButtonClicked(event) {
        let btnName = event.target.name;
        if (btnName === "BtnOTP") {
            this.doSend();
            cc.gg.tdUtil.sendTdClickOtpOnLoginPage();
        } else if (btnName === "BtnRegister") {
            await cc.gg.toastMgr.showNetWaitting();
            let channel = cc.gg.gameDataUtil.getPakageChannel();
            let result = await cc.gg.httpUtil.httpPost("/user/login/pin", { pinId: this.pinId, pinCode: this.regOtpEb.string, password: this.regPwEb.string, channel: channel });
            if (!result.succ) {
                cc.gg.toastMgr.removeNetWaitting();
                cc.gg.toastMgr.showToast(LanguageMngTs.getSentence(177));
                return;
            }

            let data = result.data;
            let uid = data.uid;
            let mobile = data.mobile_no;
            cc.gg.tdUtil.doSendTdRegistered(uid, mobile);

            let token = result.data.token;
            cc.sys.localStorage.setItem('user_token', token);
            cc.gg.httpUtil.setUserToken(token);
            cc.gg.toastMgr.removeNetWaitting();
            cc.gg.gameDataUtil.isRegister = true;
            cc.gg.gameCtl.goLobby(token);
        } else if (btnName === "BtnLogin") {
            let mobileStr = this.handlePhoneNumber(this.loginNameEb);
            if (!mobileStr) return;

            cc.gg.toastMgr.showNetWaitting();
            cc.gg.httpUtil.httpPost("/user/login/mobile", { mobileNo: mobileStr, password: this.loginPwEb.string }, function (result) {
                if (!result.succ) {
                    this.InterfaceError(result.code);
                    cc.gg.toastMgr.removeNetWaitting();
                    return;
                }

                let data = result.data;
                let uid = data.uid;
                let mobile = data.mobile_no;
                cc.gg.tdUtil.doSendTdLogin(uid, mobile);
                // cc.gg.toastMgr.showToast(cc.gg.i18n.getSentence(cc.gg.i18n.sentence.LOGIN_SUCCESS))
                cc.logfl(`游戏登陆成功, 用户名: ${result.data.username} 密码: ${result.data.password}`);
                let token = result.data.token;
                cc.sys.localStorage.setItem('user_token', token);
                cc.sys.localStorage.setItem("login_method", "mobile");
                cc.gg.httpUtil.setUserToken(token);
                cc.gg.toastMgr.removeNetWaitting();
                cc.gg.gameCtl.goLobby(token);
            }.bind(this));
        } else if (btnName === "BtnForOTP") {
            this.forgotDoSend();
            cc.gg.tdUtil.sendTdClickOtpOnLoginPage();
        }
    }

    public InterfaceError(code: number) {
        if (code == 1) {
            cc.gg.toastMgr.showToast(LanguageMngTs.getSentence(233));
        } else if (code == 2) {
            cc.gg.toastMgr.showToast(LanguageMngTs.getSentence(234));
        } else if (code == 3) {
            cc.gg.toastMgr.showToast(LanguageMngTs.getSentence(235));
        } else return;
    }

    public onThirtLoginButtonClicked(event) {
        let btnName = event.target.name;
        if (btnName === "google") {
            cc.gg.baseUtil.loginWithGoogle();
        } else if (btnName === "facebook") {
            cc.gg.baseUtil.loginWithFaceBook();
        }
    }

    public startOtpCountDown(seconds) {
        this.maxCount = seconds;
        this.otpBtnLabel.node.color = new cc.Color(90, 90, 90);
        this.otpBtn.interactable = false;
        let countDownHandler = function () {
            this.maxCount--;
            if (this.maxCount === 0) {
                this.otpBtnLabel.node.color = new cc.Color(0, 0, 0);
                this.otpBtn.interactable = true;
                this.otpBtnLabel.string = "Send again";
                this.unschedule(countDownHandler);
                return;
            }
            this.otpBtnLabel.string = "Send again(" + this.maxCount + ")";
        }.bind(this);
        this.schedule(countDownHandler, 1);
    }

    public startForGotOtpCountDown(seconds) {
        this.maxForGotCount = seconds;
        this.forgotOtpBtnLabel.node.color = new cc.Color(90, 90, 90);
        this.forgotOtpBtn.interactable = false;
        let countDownHandler = function () {
            this.maxForGotCount--;
            if (this.maxForGotCount === 0) {
                this.forgotOtpBtnLabel.node.color = new cc.Color(0, 0, 0);
                this.forgotOtpBtn.interactable = true;
                this.forgotOtpBtnLabel.string = "Send again";
                this.unschedule(countDownHandler);
                return;
            }
            this.forgotOtpBtnLabel.string = "Send again(" + this.maxForGotCount + ")";
        }.bind(this);
        this.schedule(countDownHandler, 1);
    }

    public handlePhoneNumber(eb): string {
        let mobileStr = eb.string;
        if (!cc.gg.baseUtil.isAllNumber(mobileStr)) {
            cc.gg.toastMgr.showToast("Phone number is not correct.");
            return null;
        }

        if (mobileStr.indexOf("91") !== 0) {
            mobileStr = "91" + mobileStr;
        }
        return mobileStr;
    }

    public doSend() {
        let mobileStr = this.handlePhoneNumber(this.regNameEb);
        if (!mobileStr) return;

        if (this.firstSend) {
            this.firstSend = false;
            this.doOtpSendFirst(mobileStr);
        } else {
            this.doOtpSendSecond(mobileStr);
        }
        this.startOtpCountDown(60);
    }

    public forgotDoSend() {
        let mobileStr = this.handlePhoneNumber(this.forNameEb);
        if (!mobileStr) return;

        if (this.firstForSend) {
            this.firstForSend = false;
            this.doOtpSendFirst(mobileStr);
        } else {
            this.doOtpSendSecond(mobileStr);
        }
        this.startForGotOtpCountDown(60);
    }

    public doOtpSendSecond(mobileStr: string) {
        let pinId = null;
        if (this.typeNodeNum == 1) {
            pinId = this.pinId;
        } else if (this.typeNodeNum == 2) {
            pinId = this.pinIdFro;
        }
        cc.gg.httpUtil.httpPost("/user/pin/resent", { mobileNo: mobileStr, pinId: pinId }, function (result) {
            if (!result.succ) {
                // cc.gg.toastMgr.showToast(cc.gg.i18n.getSentence(cc.gg.i18n.sentence.LOGIN_FAILED))
                cc.logfl(`验证码发送失败: ${result.msg}`);
                return;
            }
            cc.log("pincode::::::::::::::::", result);
        }.bind(this));
    }

    public doOtpSendFirst(mobileStr) {
        cc.gg.httpUtil.httpPost("/user/pin/send", { mobileNo: mobileStr }, function (result) {
            if (!result.succ) {
                // cc.gg.toastMgr.showToast(cc.gg.i18n.getSentence(cc.gg.i18n.sentence.LOGIN_FAILED))
                cc.logfl(`验证码发送失败: ${result.msg}`);
                return;
            }
            if (this.typeNodeNum == 1) {
                this.pinId = result.data.pinId;
            } else if (this.typeNodeNum == 2) {
                this.pinIdFro = result.data.pinId;
            }

            cc.log("pincode::::::::::::::::", result.data.pinId);
        }.bind(this))
    }

    public changeToLoginPage() {
        cc.log("change to login page");
        this.registerNode.active = false;
        this.loginNode.active = true;
        this.forgotNode.active = false;
        this.typeNodeNum = 0;
    }

    public changeToRegistPage() {
        this.registerNode.active = true;
        this.loginNode.active = false;
        this.forgotNode.active = false;
        this.typeNodeNum = 1;
    }

    public changeToForgotPage() {
        this.registerNode.active = false;
        this.loginNode.active = false;
        this.forgotNode.active = true;
        this.typeNodeNum = 2;
    }

    public onRegPhoneNumChanged(event) {
        this.firstSend = true;
    }

    public onForPhoneNumChanged(event) {
        this.firstForSend = true;
    }

    /**重置密码并登录 */
    public onBtnForgotPassword(event) {
        if (!this.pinIdFro || !this.forOtpEb.string || !this.forPwEb.string) return;
        cc.gg.httpUtil.httpPost("/user/profile/password/reset", { pinId: this.pinIdFro, pinCode: this.forOtpEb.string, password: this.forPwEb.string }, function (result) {
            if (!result.succ) {
                cc.logfl(`重置密码失败： ${result.msg}`);
                return;
            }
            this.onBtnForGotLogin();
        }.bind(this));
    }

    public async onBtnForGotLogin() {
        await cc.gg.toastMgr.showNetWaitting();
        cc.gg.httpUtil.httpPost("/user/login/mobile", { mobileNo: this.forNameEb, password: this.forPwEb.string }, function (result) {
            if (!result.succ) {
                this.InterfaceError(result.code);
                cc.gg.toastMgr.removeNetWaitting();
                return;
            }

            let data = result.data;
            let uid = data.uid;
            let mobile = data.mobileNo;
            cc.gg.tdUtil.doSendTdLogin(uid, mobile);
            // cc.gg.toastMgr.showToast(cc.gg.i18n.getSentence(cc.gg.i18n.sentence.LOGIN_SUCCESS))
            cc.logfl(`游戏登陆成功, 用户名: ${result.data.username} 密码: ${result.data.password}`);
            let token = result.data.token;
            cc.sys.localStorage.setItem('user_token', token);
            cc.sys.localStorage.setItem("login_method", "mobile");
            cc.gg.httpUtil.setUserToken(token);
            cc.gg.toastMgr.removeNetWaitting();
            cc.gg.gameCtl.goLobby(token);
        }.bind(this));
    }


    /**游客登录   并判断是否为第一次登录 */
    public async onGeast() {
        cc.gg.tdUtil.doSendTdEvent("click_Login_BtnGeast", "", "");
        let token = cc.sys.localStorage.getItem("user_token");
        if (token) {
            let data = await HttpAPIUtil.getRefreshToken(token);
            let newToken = data ? data.token : null;
            let uid = data ? data.uid : null;
            if (newToken) {
                cc.gg.tdUtil.doSendTdLogin(uid, "");
                cc.gg.httpUtil.setUserToken(newToken);
                cc.sys.localStorage.setItem('user_token', newToken);
                cc.sys.localStorage.setItem("login_method", "guest");
                let fbm = require("FireBaseMgr");
                fbm.sendSignUp();
                cc.gg.gameCtl.goLobby(newToken);
            } else {
                cc.gg.httpUtil.setUserToken(null);
                this.doGuestLogin();
            }
        } else {
            this.doGuestLogin();
        }
    }
}
